package cn.senwill.order_service.service.impl;

import cn.senwill.order_service.domain.Order;
import cn.senwill.order_service.feign.ProductFeignClient;
import cn.senwill.order_service.service.OrderService;
import cn.senwill.order_service.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Override
    public Object save(Integer userId, Integer productId) {
        logger.info("----save order start");
        // 调用方式1：使用ribbon的RestTemplate
        //Map<String, Object> productMap = restTemplate.getForObject("http://product-service/api/v1/product/findById?id=" + productId, Map.class);
        //System.out.println(productMap);

        // 调用方式2：使用feign的ProductServiceClient，默认集成ribbon，推荐使用
        String response = productFeignClient.findById(productId);
        Map<String, Object> productMap = JsonUtil.json2map(response);

        Order order = new Order();
        order.setCreateTime(new Date());
        order.setUserId(userId);
        order.setTradeNo(UUID.randomUUID().toString());
        order.setProductName(productMap.get("name").toString());
        order.setPrice(Double.parseDouble(productMap.get("price").toString()));
        order.setPort(productMap.get("port").toString());
        logger.info("----save order end");
        return order;
    }

}
